unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Timer1: TTimer;
    procedure FormClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private

  public

  end;

  { TMyShape }

  TMyShape = class(TShape)
    public
      sx, sy : Integer;
      procedure Click; override;
      procedure MouseEnter; override;
      procedure MouseLeave; override;
  end;

const
  count = 10;
  molWidth = 80;
var
  Form1: TForm1;

implementation

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
var i: Integer;
  buf : TMyShape;
begin
  Randomize;
  For i:=0 to count do begin
    buf := TMyShape.Create(Form1);
    buf.Width:=molWidth;
    buf.Height:=molWidth;
    buf.Left:=Random(Form1.ClientWidth);
    buf.Top:= Random(Form1.ClientHeight);
    buf.sx:=Random(1)+2;
    buf.sy:=Random(1)+2;
    buf.Shape:=stCircle;
    buf.Parent:=Form1;
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var i : Integer;
begin
  for i:=0 to Form1.ComponentCount-1 do begin
    if (Form1.Components[i] is TMyShape) then begin
      (Form1.Components[i] as TMyShape).Left:=(Form1.Components[i] as TMyShape).Left+(Form1.Components[i] as TMyShape).sx;
      (Form1.Components[i] as TMyShape).Top:=(Form1.Components[i] as TMyShape).Top+(Form1.Components[i] as TMyShape).sy;
      // анализ столкновения с правой границей
      if ((Form1.Components[i] as TMyShape).Left >=Form1.ClientWidth - (Form1.Components[i] as TMyShape).Width) then begin
        (Form1.Components[i] as TMyShape).Left:=Form1.ClientWidth-(Form1.Components[i] as TMyShape).Width;
        (Form1.Components[i] as TMyShape).sx := -(Form1.Components[i] as TMyShape).sx;
      end;
      // левая граница
      if ((Form1.Components[i] as TMyShape).Left <= 0 ) then begin
        (Form1.Components[i] as TMyShape).Left:=0;
        (Form1.Components[i] as TMyShape).sx := -(Form1.Components[i] as TMyShape).sx;
      end;

    end;
  end;
end;

procedure TForm1.FormClick(Sender: TObject);
begin
  Timer1.Enabled:=True;
end;

{ TMyShape }

procedure TMyShape.Click;
begin
  inherited Click;
end;

procedure TMyShape.MouseEnter;
begin
  inherited MouseEnter;
end;

procedure TMyShape.MouseLeave;
begin
  inherited MouseLeave;
end;

initialization
  {$I unit1.lrs}

end.

